package com.ming.yourdiary.activity;

import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.ming.yourdiary.R;
import com.ming.yourdiary.YourDiaryApplication;
import com.ming.yourdiary.adapter.MainPageViewPagerAdapter;
import com.ming.yourdiary.fragment.CalendarFragment;
import com.ming.yourdiary.fragment.DiaryNotesFragment;
import com.ming.yourdiary.fragment.MyFragment;
import com.ming.yourdiary.common.AppConstants;
import com.ming.yourdiary.util.UiTools;
import com.qweather.sdk.bean.base.Code;
import com.qweather.sdk.bean.geo.GeoBean;
import com.qweather.sdk.bean.weather.WeatherNowBean;
import com.qweather.sdk.view.QWeather;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

  private static final String TAG = "MainActivity";

  /*对应Fragment的下标index*/
  private final static int PAGE_DIARY_RECORD = 0;
  private final static int PAGE_DIARY_CALENDAR = 1;
  private final static int PAGE_DIARY_MY = 2;
  private boolean mIsViewPagerAnim = true;

  private ViewPager mAppViewPager;
  private MainPageViewPagerAdapter mViewPagerAdapter;
  private Handler mHandler = new Handler();

  private List<Fragment> mFragmentList;
  private DiaryNotesFragment mDiaryNotesFragment;
  private CalendarFragment mCalendarFragment;
  private MyFragment mMyFragment;

  /*Data*/
  private SparseIntArray mFragmentIndexMap;

  /*View*/
  private LinearLayout mTopBtnContainer;
  private ImageView mSettingBtn;
  private Button mBrowserBtn;
  private Button mCalendarBtn;
  private Button mMyBtn;
  private ImageView mChangeBtn;
  private ViewPager mViewPager;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //UiTools.setStatusBarColor(MainActivity.this,getResources().getColor(R.color.white));
    //UiTools.setTranslucentStatusBar(MainActivity.this,false);
    StatusBarUtil.setColor(MainActivity.this,getResources().getColor(R.color.theme_color));
    initView();
    initViewPager();

    getWeatherData(YourDiaryApplication.sUserLocation);
    getCityInfo(YourDiaryApplication.sUserLocation);
  }


  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  }

  private void initView() {
    mTopBtnContainer = (LinearLayout)findViewById(R.id.switch_btn_container);
    mSettingBtn = (ImageView) findViewById(R.id.setting_btn);
    mBrowserBtn = (Button) findViewById(R.id.switch_btn_browser);
    mCalendarBtn = (Button) findViewById(R.id.switch_btn_calendar);
    mMyBtn = (Button) findViewById(R.id.switch_btn_my);
    mChangeBtn = (ImageView) findViewById(R.id.change_btn);
    mViewPager = (ViewPager) findViewById(R.id.page_content_container);

    //设置圆角
    UiTools.setBgRadius(mTopBtnContainer,getResources().getDimensionPixelOffset(R.dimen.dp_10));

    mSettingBtn.setOnClickListener(mBtnClickListener);
    mBrowserBtn.setOnClickListener(mBtnClickListener);
    mCalendarBtn.setOnClickListener(mBtnClickListener);
    mMyBtn.setOnClickListener(mBtnClickListener);
    mChangeBtn.setOnClickListener(mBtnClickListener);

    mIsViewPagerAnim = true;
  }

  private void initViewPager() {
    mDiaryNotesFragment = new DiaryNotesFragment();
    mCalendarFragment = new CalendarFragment();
    mMyFragment = new MyFragment();
    mFragmentList = new ArrayList<>();

    mFragmentList.add(mDiaryNotesFragment);
    mFragmentList.add(mCalendarFragment);
    mFragmentList.add(mMyFragment);
    mViewPagerAdapter = new MainPageViewPagerAdapter(getSupportFragmentManager(), mFragmentList);
    mViewPager.setAdapter(mViewPagerAdapter);
    mViewPager.setOffscreenPageLimit(2);
    setCurrentItem();

    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
      @Override
      public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        Log.d(TAG, "onConfig onPageScrolled:" + position);
      }

      @Override
      public void onPageSelected(int position) {
        Log.d(TAG, "onConfig onPageSelected:" + position);
        switch (position) {
          case PAGE_DIARY_RECORD:
            showPage(mBrowserBtn);
            break;
          case PAGE_DIARY_CALENDAR:
            showPage(mCalendarBtn);
            break;
          case PAGE_DIARY_MY:
            showPage(mMyBtn);
            break;
        }
      }

      @Override
      public void onPageScrollStateChanged(int state) {

      }
    });
  }

  private View.OnClickListener mBtnClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
      int btnId = view.getId();
      if (btnId == R.id.switch_btn_browser) {
        mViewPager.setCurrentItem(PAGE_DIARY_RECORD, mIsViewPagerAnim);
      } else if (btnId == R.id.switch_btn_calendar) {
        mViewPager.setCurrentItem(PAGE_DIARY_CALENDAR, mIsViewPagerAnim);
      } else if (btnId == R.id.switch_btn_my) {
        mViewPager.setCurrentItem(PAGE_DIARY_MY, mIsViewPagerAnim);
      } else if (btnId == R.id.setting_btn) {
        Log.d(TAG, "============================设置按钮===============================");
      } else if (btnId == R.id.change_btn) {
        Log.d(TAG, "============================变更按钮===============================");
      }
    }
  };

  /*设置默认选中的TAB*/
  private void setCurrentItem() {
    if(mFragmentIndexMap == null){
      mFragmentIndexMap = new SparseIntArray();
    }
    mFragmentIndexMap.clear();
    mFragmentIndexMap.put(R.id.switch_btn_browser, PAGE_DIARY_RECORD);
    mFragmentIndexMap.put(R.id.switch_btn_calendar, PAGE_DIARY_CALENDAR);
    mFragmentIndexMap.put(R.id.switch_btn_my, PAGE_DIARY_MY);
    if (mViewPager != null && mViewPager != null && mViewPagerAdapter.getCount() > 0) {
      mViewPager.setCurrentItem(PAGE_DIARY_RECORD, mIsViewPagerAnim);
      showPage(mBrowserBtn);
    }
  }

  //切换Fragment显示
  private void showPage(final View view) {
    if (mHandler != null) {
      mHandler.post(new Runnable() {
        @Override
        public void run() {
          mBrowserBtn.setSelected(false);
          mCalendarBtn.setSelected(false);
          mMyBtn.setSelected(false);
          int pageIndex = mFragmentIndexMap.get(view.getId());
          switch (pageIndex) {
            case PAGE_DIARY_RECORD:
              mBrowserBtn.setSelected(true);
              Log.d(TAG, "=============================页面切换--浏览====================");
              break;
            case PAGE_DIARY_CALENDAR:
              mCalendarBtn.setSelected(true);
              Log.d(TAG, "=============================页面切换--日历===================");
              break;
            case PAGE_DIARY_MY:
              mMyBtn.setSelected(true);
              Log.d(TAG, "=============================页面切换--我的====================");
              break;
            default:
              break;
          }
        }
      });
    }
  }

  private void getWeatherData(String location) {
    if (location == null) {
      return;
    }

    /**
     * 实况天气数据
     * @param location 所查询的地区，可通过该地区名称、ID、IP和经纬度进行查询经纬度格式：经度,纬度
     *                 （英文,分隔，十进制格式，北纬东经为正，南纬西经为负)
     * @param lang     (选填)多语言，可以不使用该参数，默认为简体中文
     * @param unit     (选填)单位选择，公制（m）或英制（i），默认为公制单位
     * @param listener 网络访问结果回调
     */
    QWeather.getWeatherNow(MainActivity.this, location, new QWeather.OnResultWeatherNowListener() {
      @Override
      public void onError(Throwable e) {
        Log.i(AppConstants.WEATHER_TAG, "getWeather onError: " + e);
      }

      @Override
      public void onSuccess(WeatherNowBean weatherBean) {
        Log.i(AppConstants.WEATHER_TAG, "getWeather onSuccess: " + new Gson().toJson(weatherBean));
        if (Code.OK == weatherBean.getCode()) {
          WeatherNowBean.NowBaseBean now = weatherBean.getNow();
        } else {
          Code code = weatherBean.getCode();
          Log.i(AppConstants.WEATHER_TAG, "failed code: " + code);
        }
      }
    });
  }

  //获取所在城市信息
  private void getCityInfo(@NonNull String location) {
    QWeather.getGeoCityLookup(MainActivity.this, location, new QWeather.OnResultGeoListener() {
      @Override
      public void onError(Throwable e) {
        Log.i(AppConstants.WEATHER_TAG, "getGeoCityLookup onError: " + e);
      }

      @Override
      public void onSuccess(GeoBean geoBean) {
        Log.i(AppConstants.WEATHER_TAG, "getGeoCityLookup onSuccess: " + new Gson().toJson(geoBean));
        if (Code.OK == geoBean.getCode()) {
          List<GeoBean.LocationBean> locationBean = geoBean.getLocationBean();
        } else {
          Code code = geoBean.getCode();
          Log.i(AppConstants.WEATHER_TAG, "failed code: " + code);
        }
      }
    });

  }

}